//
//  OAuthViewController.swift
//  Weibo
//
//  Created by apple on 15/12/8.
//  Copyright © 2015年 idcast. All rights reserved.
//

import UIKit
import SVProgressHUD
/// OAuth授权控制器
class OAuthViewController: UIViewController {
    
    private lazy var webView = UIWebView()
    
    // MARK 监听方法 关闭
    @objc private func close() {
        SVProgressHUD.dismiss()
    
        dismissViewControllerAnimated(true, completion: nil)
    }
    //自动填充
    @objc private func autoFill() {
    
        let js = "document.getElementById('userId').value = 'daoge10000@sina.cn';" +
        "document.getElementById('passwd').value = 'qqq123';"
        //让webview执行js
        webView.stringByEvaluatingJavaScriptFromString(js)
    }
    //设置界面
    override func loadView() {
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: "autoFill")
        view = webView
        
        webView.delegate = self
        
        title = "登录新浪微博"
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        //加载界面
        self.webView.loadRequest(NSURLRequest(URL: NetwokeTools.sharedTools.oauthURL))
        
    }

}

//MARK UITableviewDeledate
extension OAuthViewController: UIWebViewDelegate {
    /// 将要加载请求的代理方法
    ///
    /// - parameter webView:        webView 
    /// - parameter request:        将要加载的请求
    /// - parameter navigationType: navigationType页面跳转的方式
    ///
    /// - returns: 返回ture 加载

    func webView (webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        // 1 如果是百度就不加载
        //判断主机是否是www.baidu.com
        print(request.URL)
        guard let url = request.URL where url.host == "www.baidu.com" else {
        
            return true
        }
        //2从百度的url中 提取code = 是否存在
        guard let query = url.query where query.hasPrefix("code=") else {
            print("取消授权")
            close()
            return false
        }
        
        //3 从query 字符串中提取 code= 后面的授权码
        let code = query.substringFromIndex("code=".endIndex)
        print(query)
        print("授权码是 " + code)


//        // 4. 加载 accessToken
//        NetwokeTools.sharedTools.loadAccessToken(code) { (result, error) -> () in
//            if error != nil{
//                print(error)
//            } else {
//                print(result)
//            }
//        }
        UserAccountViewModel.sharedUserAccount.loadAccessToken(code) { (isSuccessed) -> () in
            
            // finished 的完整代码
            if !isSuccessed {
                SVProgressHUD.showInfoWithStatus("您的网络不给力")
                
                delay(0.5) { self.close() }
                
                return
            }
            
            print("成功了")
            // dismissViewControllerAnimated 方法不会立即将控制器销毁
            self.dismissViewControllerAnimated(false) {
                
                // 停止指示器
                SVProgressHUD.dismiss()
                
                // 通知中心是同步的 - 一旦发送通知，会先执行监听方法，直接结束后，才执行后续代码
                NSNotificationCenter.defaultCenter().postNotificationName(WBSwitchRootViewControllerNotification, object: "welcome")
            }
        }
//
        return false
    }
    
    
       func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
        
    }
       func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }

}
